import 'dart:async';

import 'package:BeeApp/CarPage/CarOrderNewsPage.dart';
import 'package:BeeApp/CarPage/LocationNumbModel02.dart';
import 'package:BeeApp/MainPage/MainModelPage.dart';
import 'package:BeeApp/MainPage/MainOrderModel.dart';
import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CarMainPage02 extends StatefulWidget {
  CarMainPage02({Key key}) : super(key: key);

  @override
  _CarMainPage02State createState() => _CarMainPage02State();
}

class _CarMainPage02State extends State<CarMainPage02> {
  // 定时器
  Timer countDownTimer;
  int allTime = 1800;
  int nowTime = 1800;
  String endTimeStr = "0.00";
  DateTime endDate = DateTime.parse("2020-12-13 15:32:41");

  // 展示类型
  int showType = 0;

  LocationNumbModel02 locationNumbModel;
  String allNumb = "0";
  String cityStr = "";

  String chooseAddress = "";
  // 发货地址
  String sendAddress01 = "";
  String showSendAddress = "请选择";
  // 收货地址
  String shouAddress01 = "";
  String showShouAddress = "请选择";

  String otherType = "0";
  bool requested = false;

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  int page = 1;
  List<MainOrderCellModel> cellArr = [];

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    page = 1;
    cellArr?.clear();
    uploadCellData();
    requested = true;
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    // items.add((items.length + 1).toString());
    page = page + 1;
    uploadCellData();
    if (mounted) setState(() {});
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    super.initState();
    if (mounted) {
      setState(() {
        cityStr = getData("city");
      });
    }
    // upTimeDate();
    _onRefresh();
  }

  @override
  void dispose() {
    super.dispose();
    countDownTimer?.cancel();
  }

  // void upTimeDate() {
  //   DioUtils.postHttp(
  //     context,
  //     "Usercommon/user_info",
  //     parameters: {"token": getData("token")},
  //     onSuccess: (t) {
  //       print(t);
  //       MainModel model = MainModel.fromJson(t);
  //       if (model.code == 1 && model.data != null) {
  //         UserModel userModel = UserModel.fromJson(t["data"]);
  //         if (mounted) {
  //           setState(() {
  //             allTime = int.parse(userModel.reciveOrderMinit) * 60;
  //           });
  //           if (!ObjectUtil.isEmpty(userModel.reciveEndTime)) {
  //             endDate = DateTime.parse(userModel.reciveEndTime);
  //             codeGet();
  //           }
  //         }
  //       }
  //     },
  //     onError: (error) {
  //       print(error);
  //     },
  //   );
  // }

  // // 启动倒计时
  // void codeGet() async {
  //   countDownTimer?.cancel(); //如果已存在先取消置空
  //   countDownTimer = null;
  //   countDownTimer = Timer.periodic(Duration(seconds: 1), (t) {
  //     if (mounted) {
  //       Duration duration = endDate.difference(DateTime.now());
  //       if (duration.inSeconds >= 0) {
  //         if (mounted) {
  //           setState(() {
  //             endTimeStr = getCaption(duration.toString());
  //             nowTime = duration.inSeconds;
  //           });
  //         }
  //       } else {
  //         nowTime = 1800;
  //         countDownTimer.cancel();
  //         countDownTimer = null;
  //       }
  //     }
  //   });
  // }

  // 请求发货地和收货地 信息
  void uploadAddress(String urlStr) {
    DioUtils.postHttp(
      context,
      urlStr,
      parameters: {
        "token": getData("token"),
        "type": "2",
      },
      onSuccess: (t) {
        print(t);
        MainModel model = MainModel.fromJson(t);
        if (model.code == 1 && model.data != null) {
          if (mounted) {
            setState(() {
              locationNumbModel = LocationNumbModel02.fromJson(t);
              allNumb = locationNumbModel.data.total.toString();
            });
            // locationArr.add(locationNumbModel);
          }
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  // 请求订单信息
  void uploadCellData() {
    Map<String, dynamic> dic = Map();
    dic["token"] = getData("token");
    dic["s_city"] = cityStr;
    dic["type"] = "2";
    dic["page"] = page.toString();
    if (otherType != "0") {
      dic["sort"] = otherType;
    }

    if (sendAddress01.length > 0) {
      dic["s_city"] = sendAddress01;
    }

    if (shouAddress01.length > 0) {
      dic["r_city"] = shouAddress01;
    }

    showLoading(context);
    DioUtils.postHttp(
      context,
      "Caruser/orders_list",
      parameters: dic,
      onSuccess: (t) {
        print(t);
        dismissLoading(context);
        MainModel model = MainModel.fromJson(t);
        if (model.code == 1 && model.data != null) {
          if (mounted) {
            MainOrderListModel listModel = MainOrderListModel.fromJson(t);
            List<MainOrderCellModel> arr = listModel.data;
            setState(() {
              for (var i = 0; i < arr.length; i++) {
                cellArr.add(arr[i]);
              }
            });
          }
        } else {
          showToast(t["msg"]);
        }
      },
      onError: (error) {
        print(error);
        dismissLoading(context);
        showToast(error);
      },
    );
  }

  Text textLabel01(String str) {
    return Text(
      str,
      style: TextStyle(
        color: Color(0xFF666666),
        fontSize: setFontSize(28),
      ),
    );
  }

  Text textLabel02(String str) {
    return Text(
      str,
      style: TextStyle(
        color: Color(0xFF333333),
        fontSize: setFontSize(28),
      ),
    );
  }

  Text textLabel03(String str) {
    return Text(
      str,
      style: TextStyle(
        color: Color(0xFF999999),
        fontSize: setFontSize(24),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
          // codeGet();
        },
        child: Column(
          children: <Widget>[
            // timeView(),
            chooseView(),
            Expanded(
              child: Stack(
                children: <Widget>[
                  orderView(),
                  Container(
                    height: screenHeight / 2,
                    child: otherView(),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget otherView() {
    if (showType == 1) {
      return addressView();
    } else if (showType == 2) {
      return addressView();
    } else if (showType == 3) {
      return otherChoose();
    } else {
      return Container();
    }
  }

  Text topText(String string) {
    return Text(
      string,
      style: TextStyle(
        color: Color(0xFF333333),
        fontSize: setFontSize(28),
      ),
    );
  }

  Widget timeView() {
    return Stack(children: <Widget>[
      Container(
        height: setHeight(50),
        width: nowTime > 0 ? nowTime / allTime * screenWidth : 0,
        color: Color(0xFFAAE8F8),
      ),
      Container(
        height: setHeight(50),
        padding: EdgeInsets.only(left: setWidth(30)),
        alignment: Alignment.centerLeft,
        child: Text("剩余接单时间：$endTimeStr"),
      ),
    ]);
  }

  Widget chooseView() {
    return Container(
      height: setHeight(70),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black, width: 1),
        color: Color(0xFFFF7F27),
      ),
      child: Row(
        children: <Widget>[
          Container(
            width: (screenWidth - setWidth(50)) / 3,
            child: InkWell(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  // 判断展示文字的长度  和控件的长度
                  textWidth(context, showSendAddress, setFontSize(28)) >
                          (screenWidth - setWidth(50)) / 3
                      ? Expanded(
                          child: topText(showSendAddress),
                        )
                      : topText(showSendAddress),
                  Image.asset(
                    "images/ShowMoreImage.png",
                    height: setWidth(40),
                  )
                ],
              ),
              onTap: () {
                print("object");
                locationNumbModel = null;
                uploadAddress("Caruser/get_send_orders");
                if (mounted) {
                  setState(() {
                    chooseAddress = "";
                    sendAddress01 = "";
                    showType = 1;
                  });
                }
              },
            ),
          ),
          Image.asset(
            "images/MainChangeHImage.png",
            height: setWidth(50),
            width: setWidth(50),
          ),
          Container(
            width: (screenWidth - setWidth(50)) / 3,
            child: InkWell(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  // 判断展示文字的长度  和控件的长度
                  textWidth(context, showShouAddress, setFontSize(28)) >
                          (screenWidth - setWidth(50)) / 3
                      ? Expanded(
                          child: topText(showShouAddress),
                        )
                      : topText(showShouAddress),
                  Image.asset(
                    "images/ShowMoreImage.png",
                    height: setWidth(40),
                  )
                ],
              ),
              onTap: () {
                print("object");
                locationNumbModel = null;
                uploadAddress("Caruser/get_recive_orders");
                if (mounted) {
                  setState(() {
                    chooseAddress = "";
                    shouAddress01 = "";
                    showType = 2;
                  });
                }
              },
            ),
          ),
          Expanded(
            child: InkWell(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  topText("智能选择"),
                  Image.asset(
                    "images/ShowMoreImage.png",
                    height: setHeight(40),
                  )
                ],
              ),
              onTap: () {
                print("object");
                if (mounted) {
                  setState(() {
                    showType = 3;
                  });
                }
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget addressView() {
    return Container(
      padding: EdgeInsets.all(setWidth(10)),
      child: Container(
          padding: EdgeInsets.all(setWidth(20)),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(6)),
            border: Border.all(color: Color(0xFF707070), width: 1),
            color: Colors.white,
          ),
          child: ListView(children: [Wrap(children: getaddressViews())])),
    );
  }

  Widget otherChoose() {
    return Container(
      alignment: Alignment.topRight,
      padding: EdgeInsets.only(top: 5, right: 5),
      child: Column(
        children: <Widget>[
          InkWell(
            child: Container(
              decoration: BoxDecoration(
                  color: Color(0xFFFF7F27),
                  // borderRadius: BorderRadius.all(Radius.circular(6)),
                  border: Border.all(color: Color(0xFF222222), width: 1)),
              child: Container(
                margin: EdgeInsets.fromLTRB(20, 8, 20, 8),
                child: Text(
                  "距离最近",
                  style: TextStyle(
                    color: Color(0xFF333333),
                    fontSize: setFontSize(26),
                  ),
                ),
              ),
            ),
            onTap: () {
              print("object");
              if (mounted) {
                setState(() {
                  showType = 0;
                });
              }
              otherType = "1";
              _onRefresh();
            },
          ),
          SizedBox(height: 4),
          InkWell(
            child: Container(
              decoration: BoxDecoration(
                  color: Color(0xFFFF7F27),
                  // borderRadius: BorderRadius.all(Radius.circular(6)),
                  border: Border.all(color: Color(0xFF222222), width: 1)),
              child: Container(
                margin: EdgeInsets.fromLTRB(20, 8, 20, 8),
                child: Text(
                  "价格最高",
                  style: TextStyle(
                    color: Color(0xFF222222),
                    fontSize: setFontSize(26),
                  ),
                ),
              ),
            ),
            onTap: () {
              print("object");
              if (mounted) {
                setState(() {
                  showType = 0;
                });
              }
              otherType = "2";
              _onRefresh();
            },
          ),
        ],
      ),
    );
  }

  Color selectTextColor(int index) {
    if (locationNumbModel.data.list[index - 1].rCity == chooseAddress) {
      return Color(0xFF222222);
    } else {
      return Color(0xFF333333);
    }
  }

  Color selectBackColor(int index) {
    if (locationNumbModel.data.list[index - 1].rCity == chooseAddress) {
      return Color(0xFFFF7F27);
    } else {
      return Colors.white;
    }
  }

  Color selectBorderColor(int index) {
    if (locationNumbModel.data.list[index - 1].rCity == chooseAddress) {
      return Color(0xFF222222);
    } else {
      return Color(0xFF999999);
    }
  }

  List<Widget> getaddressViews() {
    List<Widget> list = [];
    if (locationNumbModel == null || locationNumbModel.data.list.length == 0) {
      list.add(dismissView());
      return list;
    }
    for (int i = 0; i < locationNumbModel.data.list.length + 1; i++) {
      if (i == 0) {
        // 添加删除按钮 点击隐藏弹窗
        list.add(dismissView());
      } else {
        list.add(addressBtnView(i));
      }
    }
    return list;
  }

  Widget dismissView() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Container(
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.only(bottom: 8),
          // Text(showType == 1 ? "请选择出发地：共$allNumb件" : "请选择目的地：共$allNumb件",
          //     style: TextStyle(
          //       color: Color(0xFF333333),
          //       fontSize: setFontSize(30),
          //     ))
          child: RichText(
            text: TextSpan(
                style: TextStyle(
                    color: Color(0xFF333333), fontSize: setFontSize(30)),
                children: <InlineSpan>[
                  TextSpan(text: showType == 1 ? "请选择出发地: 共" : "请选择目的地: 共"),
                  TextSpan(
                    text: '$allNumb',
                    style: TextStyle(
                        color: Color(0xFFFF7F27), fontSize: setFontSize(30)),
                  ),
                  TextSpan(text: "件"),
                ]),
          ),
        ),
        InkWell(
          child: Container(
            alignment: Alignment.centerRight,
            child: Image.asset(
              "images/MainDismissImage.png",
              height: setWidth(40),
            ),
          ),
          onTap: () {
            if (mounted) {
              setState(() {
                showType = 0;
                locationNumbModel = null;
              });
            }
          },
        ),
      ],
    );
  }

  Widget addressBtnView(int index) {
    return InkWell(
      child: Container(
        margin: EdgeInsets.symmetric(
            vertical: setHeight(8), horizontal: setWidth(8)),
        decoration: BoxDecoration(
            color: selectBackColor(index),
            border: Border.all(color: selectBorderColor(index), width: 1)),
        child: Container(
          margin: EdgeInsets.fromLTRB(
              setWidth(13), setHeight(14), setWidth(13), setHeight(14)),
          child: Text(
            showType == 1
                ? locationNumbModel.data.list[index - 1].sCity +
                    "  " +
                    locationNumbModel.data.list[index - 1].num.toString()
                : locationNumbModel.data.list[index - 1].rCity +
                    "  " +
                    locationNumbModel.data.list[index - 1].num.toString(),
            style: TextStyle(
              color: selectTextColor(index),
              fontSize: setFontSize(26),
            ),
          ),
        ),
      ),
      onTap: () {
        print("元素" + index.toString());
        if (showType == 1) {
          sendAddress01 = locationNumbModel.data.list[index - 1].sCity;
          setState(() {
            showSendAddress = sendAddress01;
          });
        } else {
          shouAddress01 = locationNumbModel.data.list[index - 1].rCity;
          setState(() {
            showShouAddress = shouAddress01;
          });
        }
        _onRefresh();
        if (mounted) {
          setState(() {
            showType = 0;
          });
        }
      },
    );
  }

  Widget btnView(String string) {
    return Container(
      decoration: BoxDecoration(
          color: Color(0xFFFF7F27),
          border: Border.all(color: Color(0xFF222222), width: 1)),
      child: Container(
        margin: EdgeInsets.fromLTRB(10, 8, 10, 8),
        child: Text(
          string,
          style: TextStyle(
            color: Color(0xFF222222),
            fontSize: setFontSize(26),
          ),
        ),
      ),
    );
  }

  Widget orderView() {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      header: WaterDropHeader(),
      footer: CustomFooter(
        builder: (BuildContext context, LoadStatus mode) {
          Widget body;
          if (mode == LoadStatus.idle) {
            body = Text("上拉加载");
          } else if (mode == LoadStatus.loading) {
            body = CupertinoActivityIndicator();
          } else if (mode == LoadStatus.failed) {
            body = Text("加载失败！点击重试！");
          } else if (mode == LoadStatus.canLoading) {
            body = Text("松手,加载更多!");
          } else {
            body = Text("没有更多数据了!");
          }
          return Container(
            height: 55.0,
            child: Center(child: body),
          );
        },
      ),
      controller: _refreshController,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: cellArr.length == 0
          ? requested
              ? Center(child: Text('暂无订单'))
              : Container()
          : ListView.builder(
              itemCount: cellArr.length,
              itemBuilder: _listItemBuilder,
            ),
    );
  }

  Widget _listItemBuilder(BuildContext context, int index) {
    return InkWell(
      onTap: () {
        String orderID = cellArr[index].id.toString();
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => CarOrderNewsPage(orderID)),
        ).then((value) {
          // upTimeDate();
          _onRefresh();
        });
      },
      child: Container(
        color: Color(0xFFEFF3F6),
        padding: EdgeInsets.only(top: setHeight(10)),
        child: Container(
          padding: EdgeInsets.fromLTRB(
            setWidth(30),
            setHeight(10),
            setWidth(30),
            setHeight(10),
          ),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  textLabel01(cellArr[index].createtimeText),
                  Expanded(
                    child: Text(
                      "备注：${cellArr[index].goodsRemark}",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: Color(0xFF666666),
                        fontSize: setFontSize(28),
                      ),
                    ),
                  )
                ],
              ),
              Row(
                // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  SizedBox(width: setWidth(10)),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: <Widget>[
                            textLabel02(
                                "${cellArr[index].sArea} · ${cellArr[index].sTitle}"),
                            SizedBox(width: 4),
                            textLabel03(cellArr[index].csDistance == null
                                ? "0.00km"
                                : "${(NumUtil.getNumByValueDouble(cellArr[index].csDistance, 2)).toStringAsFixed(2)}km"),
                            Spacer(),
                            Container(
                              // color: Colors.red,
                              alignment: Alignment.centerRight,
                              child: Text(
                                "${cellArr[index].orderPrice}元",
                                style: TextStyle(
                                  color: Color(0xFF222222),
                                  fontSize: setFontSize(36),
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            )
                          ],
                        ),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: <Widget>[
                            textLabel02(
                                "${cellArr[index].rArea} · ${cellArr[index].rTitle}"),
                            SizedBox(width: 4),
                            textLabel03(cellArr[index].rTown),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}
